package models

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"gitee.com/liuziloong/ga1400gateway/config"
	"gitee.com/liuziloong/ga1400gateway/tools"
	"gitee.com/liuziloong/ga1400gateway/tools/logs"
	"net"
	"net/http"
	"os"
	"strings"
	"time"
)

func httpRequest(method, requestURL string, requestBody []byte) {
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(network, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(network, addr, time.Second*time.Duration(config.HttpOvertime)) //设置建立连接超时
				if err != nil {
					return nil, err
				}
				conn.SetDeadline(time.Now().Add(time.Second * time.Duration(config.HttpOvertime))) //设置发送接受数据超时
				return conn, nil
			},
			ResponseHeaderTimeout: time.Second * time.Duration(config.HttpOvertime),
		},
	}

	request, err := http.NewRequest(method, requestURL, bytes.NewReader(requestBody))
	if err != nil {
		logs.BeeLogger.Error("HttpRequest ---> http.NewRequest() error:%s", err)
		return
	}

	_, err = client.Do(request)
	if err != nil {
		logs.BeeLogger.Error("HttpRequest ---> client.Do() error:%s", err)
		return
	}

	return
}

//人脸资源
func Faces(requestBody []byte, host string) interface{} {
	//logs.BeeLogger.Debug("HTTP 1400 facesHandle body:%s", string(requestBody))
	faceListObjectData := faceListObjectPacket{}
	err := json.Unmarshal(requestBody, &faceListObjectData)
	if err != nil {
		logs.BeeLogger.Error("facesHandle ---> json.Unmarshal() error:%s", err)
		return nil
	}

	for _, v := range faceListObjectData.FaceListObject.FaceObject {
		for _, imageData := range v.SubImageList.SubImageInfoObject {
			if imageData.ImageID == v.SourceID {
				//带文字说明的图片ID
				fmt.Printf("%s facesHandle ---> this is TextImage, ImageID=%s\n", time.Now().Format("2006-01-02 15:04:05"), imageData.ImageID)
				logs.BeeLogger.Notice("facesHandle ---> this is TextImage, ImageID=%s", imageData.ImageID)
			} else {
				fmt.Printf("%s facesHandle ---> ImageID=%s\n", time.Now().Format("2006-01-02 15:04:05"), imageData.ImageID)
				logs.BeeLogger.Notice("facesHandle ---> ImageID=%s", imageData.ImageID)
			}

			imageName := tools.StringsJoin(config.ImageFacesPath, "/", imageData.ImageID, ".", strings.ToLower(imageData.FileFormat))
			go fileSave(imageName, imageData.Data)
		}
	}

	//发送数据给HTTP服务端
	for _, v := range config.HttpAddressList {
		go httpRequest("POST", tools.StringsJoin(v, "/VIID/Faces"), requestBody)
	}

	facesDataReply := &facesPacketReply{ResponseStatusObject: responseStatusObject{
		RequestURL:   tools.StringsJoin("http://", host, "/VIID/Faces"),
		StatusCode:   0,
		StatusString: "正常",
		Id:           faceListObjectData.FaceListObject.FaceObject[0].FaceID,
		LocalTime:    time.Now().Format("20060102150405"),
	}}
	return facesDataReply
}

//人员资源
func Persons(requestBody []byte, host string) interface{} {
	//logs.BeeLogger.Debug("HTTP 1400 personsHandle body:%s", string(requestBody))
	personListObjectData := personListObjectPacket{}
	err := json.Unmarshal(requestBody, &personListObjectData)
	if err != nil {
		logs.BeeLogger.Error("personsHandle ---> json.Unmarshal() error:%s", err)
		return nil
	}

	for _, v := range personListObjectData.PersonListObject.PersonObject {
		for _, imageData := range v.SubImageList.SubImageInfoObject {
			if imageData.ImageID == v.SourceID {
				//带文字说明的图片ID
				fmt.Printf("%s personsHandle ---> this is TextImage, ImageID=%s\n", time.Now().Format("2006-01-02 15:04:05"), imageData.ImageID)
				logs.BeeLogger.Notice("personsHandle ---> this is TextImage, ImageID=%s", imageData.ImageID)
			} else {
				fmt.Printf("%s personsHandle ---> ImageID=%s\n", time.Now().Format("2006-01-02 15:04:05"), imageData.ImageID)
				logs.BeeLogger.Notice("personsHandle ---> ImageID=%s", imageData.ImageID)
			}

			imageName := tools.StringsJoin(config.ImagePersonsPath, "/", imageData.ImageID, ".", strings.ToLower(imageData.FileFormat))
			go fileSave(imageName, imageData.Data)
		}
	}

	//发送数据给HTTP服务端
	for _, v := range config.HttpAddressList {
		go httpRequest("POST", tools.StringsJoin(v, "/VIID/Persons"), requestBody)
	}

	personDataReply := &personPacketReply{ResponseStatusObject: responseStatusObject{
		RequestURL:   tools.StringsJoin("http://", host, "/VIID/Persons"),
		StatusCode:   0,
		StatusString: "正常",
		Id:           personListObjectData.PersonListObject.PersonObject[0].PersonID,
		LocalTime:    time.Now().Format("20060102150405"),
	}}
	return personDataReply
}

//保存图片到本地
func fileSave(fileName, fileData string) {
	file, err := os.Create(fileName)
	defer file.Close()
	if err != nil {
		logs.BeeLogger.Error("fileSave() ---> os.Create() error: %s", err)
		return
	}

	fileDataByte, err := base64.StdEncoding.DecodeString(fileData)
	if err != nil {
		logs.BeeLogger.Error("fileSave() ---> base64.StdEncoding.DecodeString() error: %s", err)
		return
	}
	_, err = file.Write([]byte(fileDataByte))
	if err != nil {
		logs.BeeLogger.Error("fileSave() ---> file.Write() error: %s", err)
		return
	}

	//fmt.Println("图片保存成功")
}
